﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace CornerMemo
{
    /// <summary>
    /// 列表展示
    /// </summary>
    public class UIListForm : UIFormEscape
    {
        [Header("列表1展示")]
        public Transform itemParent;
        public GameObject itemPrefab;
        public UIItemListManager<TestUIItemData, TestUIItem> ItemListManager;
        public List<TestUIItemData> DataList = new List<TestUIItemData>();
        [Header("列表2展示")]
        public Transform itemParent2;
        public UIItemFilterListManager<TestUIItemData, TestUIItem> ItemListManager2;
        public Button preBtn2;
        public Button nextBtn2;
        public Text pageText2;
        public Toggle toggle;
        public Image filterImage;
        public Button refreshBtn2;
        
        public override void OnInit()
        {
            ItemListManager = new UIItemListManager<TestUIItemData, TestUIItem>(itemParent, itemPrefab, DataList, 
                ShowAction, HideAction);
            ItemListManager2 = new UIItemFilterListManager<TestUIItemData, TestUIItem>(itemParent2, itemPrefab, 
                DataList, ShowAction, HideAction, UpdatePageText,16);
            preBtn2.onClick.AddListener(ItemListManager2.PrePage);
            nextBtn2.onClick.AddListener(ItemListManager2.NextPage);
            refreshBtn2.onClick.AddListener(RefreshListBtn2);
        }

        public override void OnOpen(object userData = null)
        {
            base.OnOpen(userData);
            ItemListManager.RefreshPage(dataList:DataList);
            RefreshListBtn2();
        }
        
        private void ShowAction(TestUIItemData data, TestUIItem item)
        {
            item.gameObject.SetActive(true);
            item.SetData(data);
        }
        
        private void HideAction(TestUIItem item)
        {
            item.gameObject.SetActive(false);
        }

        private void UpdatePageText()
        {
            pageText2.text = $"{ItemListManager2.PageIndex+1}/{ItemListManager2.GetPageMax}";
        }

        private void RefreshListBtn2()
        {
            if (toggle.isOn)
            {
                var filterColor = new Func<TestUIItemData, bool>(FilterColor);
                ItemListManager2.RefreshPage(filterRules:filterColor);
            }
            else
            {
                ItemListManager2.RefreshPage(filterRules: _ => true);
            }
        }

        private bool FilterColor(TestUIItemData arg)
        {
            return arg.Color == filterImage.color;
        }
    }
}